import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
import 'package:ty_smart_watch/bean/alarm_bean.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/protocol_data_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/page/watch_setting_page/controller/watch_setting_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class WatchAlarmSettingPage extends StatefulWidget {
  const WatchAlarmSettingPage({super.key});

  @override
  State<WatchAlarmSettingPage> createState() => _WatchAlarmSettingPageState();
}

class _WatchAlarmSettingPageState extends State<WatchAlarmSettingPage> {
  int _functionId = 0; //功能id
  String _mac = ""; //设备地址
  final _controller = Get.put(WatchSettingController());
  final int _ALARM_TYPE_NEW = 0;
  final int _ALARM_TYPE_MODIFY = 1;
  final int _ALARM_TYPE_DELETE = 2;

  final _confirmColor = const Color(0xFF3075E9);
  final _unConfirmColor = const Color(0xFF80A3DF);

  final List<String> _repeatWeekdayList = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

  @override
  void initState() {
    super.initState();
    _functionId = Get.arguments["id"];
    _mac = Get.arguments["mac"];
    Log.d("页面收到的数据：$_functionId > $_mac");
    _controller.getBleData(_mac, _functionId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("闹钟"),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        actions: [
          IconButton(
              onPressed: () {
                TimeOfDay timeOfDay = TimeOfDay.now();
                _createAlarmDialog(_mac, _ALARM_TYPE_NEW, 0, timeOfDay.hour, timeOfDay.minute, true,
                    false, [0, 0, 0, 0, 0, 0, 0]);
              },
              icon: const Icon(
                Icons.add_circle_outline_outlined,
                // color: Colors.red,
              ))
        ],
      ),
      body: Obx(
        () => ListView.builder(
          itemCount: _controller.alarmList.value.length,
          itemBuilder: (BuildContext context, int index) {
            final item = _controller.alarmList.value[index];
            return Container(
              margin: const EdgeInsets.fromLTRB(10, 10, 10, 0),
              padding: const EdgeInsets.symmetric(horizontal: 10),
              decoration: const BoxDecoration(
                  border: Border(bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
              child: ListTile(
                splashColor: Colors.transparent,
                onTap: () {
                  _createAlarmDialog(_mac, _ALARM_TYPE_MODIFY, item.id, item.hour, item.minute,
                      item.state == 1, item.repeat == 1, item.weekdayList);
                },
                onLongPress: () {
                  _deleteAlarmDialog(item);
                },
                trailing: Switch(
                  inactiveThumbColor: _unConfirmColor,
                  inactiveTrackColor: _unConfirmColor.withAlpha(88),
                  activeColor: _confirmColor,
                  activeTrackColor: _confirmColor.withAlpha(88),
                  onChanged: (bool value) {
                    Log.d("switch value :  $value");
                    _toggle(item);
                  },
                  value: item.state == 1,
                ),
                title: Text("${formatNumber(item.hour)}:${formatNumber(item.minute)}"),
                subtitle: Text(_getRepeat(item)),
                contentPadding: const EdgeInsets.symmetric(vertical: 2),
              ),
            );
          },
        ),
      ),
    );
  }

  String formatNumber(int number) {
    String res = "$number";
    if (number < 10) {
      res = "0$number";
    }
    return res;
  }

  String _getRepeat(AlarmBean item) {
    String weekDay = "";
    if (item.repeat == 0) {
      weekDay = "单次";
    } else {
      for (int i = 0; i < item.weekdayList.length; i++) {
        if (item.weekdayList[i] == 1) {
          weekDay += _repeatWeekdayList[i];
        }
      }
    }
    return weekDay;
  }

  ///删除闹钟
  _deleteAlarm(AlarmBean item) {
    Log.d("删除 ${item.id}");
    commitToWatch(_ALARM_TYPE_DELETE, item.id, item.state, item.repeat == 1, item.hour, item.minute,
        item.weekdayList);
  }

  ///删除闹钟弹窗
  _deleteAlarmDialog(AlarmBean item) {
    Get.defaultDialog(
      title: "删除闹钟",
      backgroundColor: Colors.white,
      // middleText: "",
      // content: ,
      //确定按钮
      confirm: ElevatedButton(
        onPressed: () {
          //单击后删除弹框
          _deleteAlarm(item);
          Get.back();
        },
        child: const Text(
          "删除",
          style: TextStyle(color: Colors.red),
        ),
      ),
      //取消按钮
      cancel: ElevatedButton(
        onPressed: () {
          //单击后删除弹框
          Get.back();
        },
        child: const Text(
          "取消",
          style: TextStyle(color: Colors.black),
        ),
      ),
    );
  }

  ///闹钟开关
  _toggle(AlarmBean alarm) {
    int raw = alarm.state; // 原始状态： 0.关闭 1.打开
    int state = (raw + 1) % 2;
    Log.d("开关原始状态: $raw  >>  修改后开关状态：$state");

    commitToWatch(_ALARM_TYPE_MODIFY, alarm.id, state, alarm.repeat == 1, alarm.hour, alarm.minute,
        alarm.weekdayList);
  }

  ///闹钟弹窗
  _createAlarmDialog(String mac, int type, int id, int hour, int minute, bool isSwitch, bool repeat,
      List<int> dayList) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlarmDialog(
          mac: mac,
          type: type,
          id: id,
          hour: hour,
          minute: minute,
          isSwitch: isSwitch,
          repeat: repeat,
          repeatWeekday: dayList,
        );
      },
    );
  }

  commitToWatch(
      int type, int id, int isSwitch, bool repeat, int hour, int minute, List<int> dayOfWeek) {
    var data = ProtocolDataUtil.alarm(type, id, isSwitch, repeat, hour, minute, dayOfWeek);
    var res = BleUtil.makeWriteData(functionId: ALARM, data: data);
    BleUtil.writeBleData(_mac, res);
  }
}

class AlarmDialog extends StatefulWidget {
  final String mac; // 设备mac
  final int type; //新建/修改
  final int id; //闹钟id
  final int hour; //时
  final int minute; //分
  final bool isSwitch; //开关
  final bool repeat; //是否重复
  final List<int> repeatWeekday;

  const AlarmDialog(
      {super.key,
      required this.mac,
      required this.type,
      required this.id,
      required this.hour,
      required this.minute,
      required this.isSwitch,
      required this.repeat,
      required this.repeatWeekday}); //重复闹钟星期

  @override
  _AlarmDialogState createState() => _AlarmDialogState();
}

class _AlarmDialogState extends State<AlarmDialog> {
  final _confirmColor = const Color(0xFF3075E9);
  final _unConfirmColor = const Color(0xFF80A3DF);

  late int _type; //新建/修改
  late int _id; //闹钟id
  late int _hour; //时
  late int _minute; //分
  late bool _isSwitch; //是否重复
  late bool _repeat; //是否重复
  late List<int> _repeatWeekday; //重复闹钟星期

  late String _mac;

  @override
  void initState() {
    super.initState();
    _mac = widget.mac;
    _type = widget.type;
    _id = widget.id;
    _hour = widget.hour;
    _minute = widget.minute;
    _isSwitch = widget.isSwitch;
    _repeat = widget.repeat;
    _repeatWeekday = widget.repeatWeekday;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
      title: const Text('新建闹钟'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TimePicker(
            onTimeChanged: (TimeOfDay time) {
              setState(() {
                _hour = time.hour;
                _minute = time.minute;
              });
            },
            hour: _hour,
            minute: _minute,
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text("重复"),
              Transform.scale(
                scale: 0.7,
                child: Switch(
                  inactiveThumbColor: _unConfirmColor,
                  inactiveTrackColor: _unConfirmColor.withAlpha(88),
                  activeColor: _confirmColor,
                  activeTrackColor: _confirmColor.withAlpha(88),
                  value: _repeat,
                  onChanged: (v) {
                    setState(() {
                      _repeat = v;
                    });
                  },
                ),
              ),
            ],
          ),
          Text('$_hour:$_minute'),
          Visibility(
            visible: _repeat,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                RoundCheckBox(
                  isChecked: _repeatWeekday[0]==1,
                  onTap: (b) {
                    _repeatWeekday[0] = b! ? 1 : 0;
                  },
                  size: 26,
                  checkedColor: _unConfirmColor,
                  checkedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("一"),
                  ),
                  uncheckedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("一"),
                  ),
                ),
                RoundCheckBox(
                  isChecked: _repeatWeekday[1]==1,
                  onTap: (b) {
                    _repeatWeekday[1] = b! ? 1 : 0;
                  },
                  size: 26,
                  checkedColor: _unConfirmColor,
                  checkedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("二"),
                  ),
                  uncheckedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("二"),
                  ),
                ),
                RoundCheckBox(
                  isChecked: _repeatWeekday[2]==1,
                  onTap: (b) {
                    _repeatWeekday[2] = b! ? 1 : 0;
                  },
                  size: 26,
                  checkedColor: _unConfirmColor,
                  checkedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("三"),
                  ),
                  uncheckedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("三"),
                  ),
                ),
                RoundCheckBox(
                  isChecked: _repeatWeekday[3]==1,
                  onTap: (b) {
                    _repeatWeekday[3] = b! ? 1 : 0;
                  },
                  size: 26,
                  checkedColor: _unConfirmColor,
                  checkedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("四"),
                  ),
                  uncheckedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("四"),
                  ),
                ),
                RoundCheckBox(
                  isChecked: _repeatWeekday[4]==1,
                  onTap: (b) {
                    _repeatWeekday[4] = b! ? 1 : 0;
                  },
                  size: 26,
                  checkedColor: _unConfirmColor,
                  checkedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("五"),
                  ),
                  uncheckedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("五"),
                  ),
                ),
                RoundCheckBox(
                  isChecked: _repeatWeekday[5]==1,
                  onTap: (b) {
                    _repeatWeekday[5] = b! ? 1 : 0;
                  },
                  size: 26,
                  checkedColor: _unConfirmColor,
                  checkedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("六"),
                  ),
                  uncheckedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("六"),
                  ),
                ),
                RoundCheckBox(
                  isChecked: _repeatWeekday[6]==1,
                  onTap: (b) {
                    _repeatWeekday[6] = b! ? 1 : 0;
                  },
                  size: 26,
                  checkedColor: _unConfirmColor,
                  checkedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("日"),
                  ),
                  uncheckedWidget: const Align(
                    alignment: Alignment.center,
                    child: Text("日"),
                  ),
                ),
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              MaterialButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: const Text('取消'),
              ),
              MaterialButton(
                onPressed: () {
                  commitToWatch(
                      _type, _id, _isSwitch ? 1 : 0, _repeat, _hour, _minute, _repeatWeekday);
                  Navigator.of(context).pop();
                },
                child: const Text('保存'),
              ),
            ],
          )
        ],
      ),
    );
  }

  commitToWatch(
      int type, int id, int isSwitch, bool repeat, int hour, int minute, List<int> dayOfWeek) {
    var data = ProtocolDataUtil.alarm(type, id, isSwitch, repeat, hour, minute, dayOfWeek);
    var res = BleUtil.makeWriteData(functionId: ALARM, data: data);
    Log.d("重复星期:$dayOfWeek");
    Log.d("闹钟数据:$res");
    BleUtil.writeBleData(_mac, res);
  }
}

class TimePicker extends StatelessWidget {
  final int hour;
  final int minute;
  final ValueChanged<TimeOfDay> onTimeChanged;

  const TimePicker({
    required this.onTimeChanged,
    required this.hour,
    required this.minute,
  });

  @override
  Widget build(BuildContext context) {
    print("初始时间:$hour,$minute");
    return SizedBox(
      height: 200.0,
      child: CupertinoTheme(
        data: const CupertinoThemeData(
          brightness: Brightness.light,
        ),
        child: CupertinoDatePicker(
          mode: CupertinoDatePickerMode.time,
          initialDateTime: DateTime(1, 1, 1, hour, minute),
          onDateTimeChanged: (DateTime dateTime) {
            onTimeChanged(TimeOfDay.fromDateTime(dateTime));
          },
          use24hFormat: true, // 设置为24小时制
        ),
      ),
    );
  }
}
